package com.lx.controller;

import com.lx.service.EmailService;
import com.lx.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 2025/9/12 23:20
 * author: 向远洋
 */
@RestController
@RequestMapping("/api")
public class EmailController {
    @Autowired
    private EmailService emailService;
    @Autowired
    private StringRedisTemplate stringRedis;

    @PostMapping("/email")
    public Result sendEmail(@RequestBody Map<String, Object> params) {
        try {
            String email = params.get("emailAddress").toString();
            String code = generateNumericCode(6);
            /*String subject = params.get("title").toString();
            String content = params.get("content").toString();*/
            emailService.sendMimeMail(email, "【注册验证码】", "验证码：" + code + "。请在一分钟内完成验证");
            stringRedis.opsForValue().set(email, code, 15, TimeUnit.MINUTES);
            return Result.success(5200, "邮箱发送成功");
        } catch (Exception e) {
            return Result.success(5500, "邮箱发送失败");
        }
    }

    private String generateNumericCode(int length) {
        StringBuffer code = new StringBuffer(length + 5);
        for(int i = 0; i < length; i++) {
            code.append((int)(Math.random() * 10));
        }
        return code.toString();
    }
}